#!/bin/bash

# 加载配置
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "${SCRIPT_DIR}/config.sh"

# 检查权限和环境
check_root
check_install_env

info "当前位置: $(pwd)"

# 从services.json获取服务列表
SERVICES=$(jq -r '.start_order | .[]' services.json)
if [ -z "$SERVICES" ]; then
    error "无法从services.json获取服务列表"
fi

# 检查所有微服务状态
info "检查微服务状态..."
total=$(echo "$SERVICES" | wc -w)

current=1
failed=0

echo "----------------------------------------"
for service in $SERVICES; do
    if pid=$(pgrep -f "${service}\$"); then
        uptime=$(ps -o etime= -p "$pid")
        cmd=$(ps -p "$pid" -o cmd=)
        info "[$current/$total] ${service} 正在运行"
        echo "  - 进程ID: $pid"
        echo "  - 运行时间: $uptime"
        echo "  - 完整路径: $cmd"
        echo "  - 日志目录: $FDSMASTERGO_LOG_DIR/${service}"
    else
        warn "[$current/$total] ${service} 未运行"
        echo "  - 日志目录: $FDSMASTERGO_LOG_DIR/${service}"
        failed=$((failed + 1))
    fi
    echo "----------------------------------------"
    current=$((current + 1))
done

# 输出总结
info "状态检查完成:"
echo "  - 总服务数: $total"
echo "  - 运行中: $((total - failed))"
echo "  - 未运行: $failed"

# 如果有服务未运行，返回非零状态码
[ $failed -eq 0 ] || exit 1

